const moment = require('moment');
const db = require('./index.js');
const utilx = require('../lib/utilx');
const User = db.models.User;
const BrowsePrivileges = db.models.BrowsePrivileges;
const ApprovalPrivileges = db.models.ApprovalPrivileges;
const Department = db.models.Department;
const DutyShift = db.models.DutyShift;
const Equipment = db.models.Equipment;
const EquipmentAttribute = db.models.EquipmentAttribute;
const InspectionFile = db.models.InspectionFile;
const InspectionRecord = db.models.InspectionRecord;
const RequestNote = db.models.RequestNote;
const WorkingSchedule = db.models.WorkingSchedule;
const Notification = db.models.Notification;
const UserRequestNote = db.models.UserRequestNote;
const workingScheduleConfig = require('../../../config/workingSchduleConfig');
const superuserConfig = require('../../../config/superuserConfig');
const equipmentConfig = require('../../../config/equipmentConfig');


// TODO：用sequelize.import方法定义的model的instanceMethods等是不能用的
let users = [];
let departments = [];

async function DepartmentSeed() {
  console.log('DepartmentSeed');
  let department;
  for( let i = 0; i < 5; i++ ) {
    department = await Department.create({
      name: `部门${i}`,
      description: `这里是部门${i}`,
    });
    departments.push(department);
  }
}

async function UserSeed() {
  console.log('UserSeed');
  let user;
  for( let i = 0; i < 10; i++ ) {
    user = await User.create({
      username: `用户${i}`,
      teamName: ['A组', 'B组', 'C组', 'D组', '无'][i % 5],
      isTeamLeader: i < 4,
      password: 'password',
      DepartmentId: departments[i % departments.length].id,
    });
    await ApprovalPrivileges.create({
      type: ['Construction', 'RequestChange', 'ExternalTest', 'ProjectTest', 'Maintain'][i % 5],
      step: 1,
      UserId: user.id,
    });
    users.push(user);
  }
}

async function NotificationSeed() {
  console.log('NotificationSeed');
  for(let i = 0; i < 20; i ++) {
    await Notification.create({
      title: `通知文件${i}`,
      filename: `文件名${i}`,
      createdTime: true,  // 利用set
      downloadUrl: `http://#`,
    });
  }
}

async function DutyShiftSeed() {
  console.log('DutyShiftSeed');
  for(let i = 0; i < 10; i++ ) {
    await DutyShift.create({
      workBeginTime: '2019年4月1日9:00',
      workEndTime: '2019年4月2日1:00',
      teamName: ['A组', 'B组', 'C组', 'D组', ''][i % 5],
      workRecord: `这里是工作记录${i}`,
      posun: `破损${i}`,
      yichang: `异常${i}`,
      chaxundan: `查询单${i}`,
    })
  }
}

/**
 * 由于是每四天循环一次，所以一次性生成1年 = - =
 */
async function WorkingScheduleSeed({ yearStart, yearEnd, monthStart, monthEnd, dayStart, dayEnd }) {
  console.log('WorkingScheduleSeed');
  monthStart = monthStart || 1;
  monthEnd = monthEnd || 12;
  dayStart = dayStart || 1;
  dayEnd = dayEnd || moment({ year: yearStart, month: monthEnd }).daysInMonth();
  monthStart -= 1;    // 程序世界里month从0开始，开放给用户的是正常思维
  monthEnd -= 1;

  let counter = 0;
  let scheduleArr = [];
  for( let year = yearStart; year <= yearEnd; year += 1) {

    let month = (year === yearStart) ? monthStart : 1;
    for(;  month <= ( year === yearEnd ? monthEnd : 11); month += 1) {

      let day = (year === yearStart && month === monthStart) ? dayStart : 1;
      for(; day <= ( year === yearEnd && month === monthEnd ? dayEnd : moment({year, month}).daysInMonth() ); day += 1, counter += 1) {
        scheduleArr.push({
          // scheduleTime: '8:00—19:30',
          startTime: {
            year,
            month,
            day,
            startHour: 8,
            startMinute: 0,
          },
          endTime: {
            year,
            month,
            day,
            startHour: 8,
            startMinute: 0,
            endHour: 19,
            endMinute: 0,
          },
          startHour: 8,
          startMinute: 0,
          endHour: 19,
          endMinute: 0,
          scheduleType: '白班',
          teamName: ['A组', 'C组', 'D组', 'B组'][counter % 4],
          year,
          month: month,
          day: day,
        });
        scheduleArr.push({
          // scheduleTime: '19:00-8:30',
          startTime: {
            year,
            month,
            day,
            startHour: 19,
            startMinute: 0,
          },
          endTime: {
            year,
            month,
            day,
            startHour: 19,
            startMinute: 0,
            endHour: 8,
            endMinute: 30,
          },
          startHour: 19,
          startMinute: 0,
          endHour: 8,
          endMinute: 30,
          scheduleType: '夜班',
          teamName: ['B组', 'A组', 'C组', 'D组'][counter % 4],
          year,
          month: month,
          day: day,
        });
      }
    }
  }
  await WorkingSchedule.bulkCreate(scheduleArr);
}

async function EquipmentSeed() {
  console.log('EquipmentSeed');
  let equipments = [];
  for(let i = 0; i < 100; i += 1) {
    equipments.push({
      name: `设备${i}`,
      description: `设备描述${i}`,
      scope: `设备类别${i % 5}`,
      radios: ['无有', '正常故障'][i % 2],
      type: ['oracle', 'bnw', 'bhics', 'bhics2', 'it', 'workstation'][i % 6],
      label: ['白', '晚'][i % 2],
    });
  }
  equipments = await Equipment.bulkCreate(equipments);
  let attributes = [];
  for( let equipment of equipments) {
    if(equipment.type === 'oracle'
      || equipment.type === 'bnw'
      || equipment.type === 'bhics'
      || equipment.type === 'bhics2'
    ) {
      for (let j = 0; j < 24; j += 0.5) {
        attributes.push({
          value: j,
          EquipmentId: equipment.id,
        });
      }
    } else {
      for (let j = 1; j <= 7; j += 1) {
        attributes.push({
          value: j,
          EquipmentId: equipment.id,
        });
      }
    }
  }
  await EquipmentAttribute.bulkCreate(attributes);
}

/**
 * 这个函数不能用bulkCreate，因为hooks里面没有afterBulkCreate
 */
async function InspectionFileAndRecordSeed() {
  console.log('InspectionFileAndRecordSeed');
  for(let i = 0; i < 10; i += 1) {
    await InspectionFile.create({
      oid: i,
      title: '检查单',
      type: ['oracle', 'bnw', 'bhics', 'bhics2', 'it', 'workstation'][i % 6],
      isAbnormal: false,
      abnormalRecord: '错误日志记录',
      daySignatory: '张三',
      nightSignatory: '王二麻子',
      superSignatory: '李二',
      createdTime: true,
    });
  }
}

async function RequestNoteSeed() {
  console.log('RequestNoteSeed');
  let notes = [];
  for(let i = 0; i < 50; i += 1 ) {
    notes.push({
      oid: i,
      type: ['Construction', 'RequestChange', 'ExternalTest', 'Maintain', 'ProjectTest'][i % 5],
      title: `申请单${i}`,
      step: [0, 1][i % 2],
      UserId: users[i % 10].id,
      userStatus: ['未提交', '审批中', '进行中', '已关闭', '未通过'][i % 5],
      createdTime: true,
    });
  }
  notes = await RequestNote.bulkCreate(notes);
  let userNotes = [];
  for( let note of notes ) {
    let step = 0;
    for( let user of users ) {
      userNotes.push({
        UserId: user.id,
        RequestNoteId: note.id,
        signCreatedTime: true,
        step,
      });
      step = (step + 1) % 8;
      if( step === 0 ) {  // 如果已经满了就break
        break;
      }
    }
  }
  await UserRequestNote.bulkCreate(userNotes);
}

async function SuperUserInitByConfig({ username, password, email, phone }) {
  let department = await Department.create({
    name: '超级管理员',
    description: '超级管理员组',
    teamName: '无',
  });
  let user = await User.create({
    username,
    password,
    email,
    phone,
    DepartmentId: department.id,
  });
  await BrowsePrivileges.update({  // 给予所有控制权限
    dashboardView: true,
    dashboardEdit: true,
    workingScheduleView: true,
    workingScheduleEdit: true,
    dutyShiftView: true,
    inspectionListView: true,
    inspectionSupport: true,
    requestNoteView: true,
    approvalListView: true,
    equipmentControlView: true,
    userControlView: true,
    groupControlView: true,
    settingsView: true,
    fileShareView: true,
    fileShareEdit: true,
  }, {
    where: {
      DepartmentId: department.id,
    }
  });
}

async function EquipmentInitByConfig(equipmentsArr) {
  for(let file of equipmentsArr) {
    let type = file.type;
    let equipmentCreateArr = [];
    let attributeCreateArr = [];
    let equipments = file.equipments;
    for( let equipment of equipments ) {
      equipmentCreateArr.push({
        name: equipment.name,
        scope: equipment.scope,
        description: equipment.description,
        radios: equipment.radios,
        label: equipment.label,
        type,
      });
    }
    equipmentCreateArr = await Equipment.bulkCreate(equipmentCreateArr);
    for( let i = 0; i < equipments.length; i += 1) {
      for(let value of equipments[i].values) {
        attributeCreateArr.push({
          value,
          EquipmentId: equipmentCreateArr[i].id,
        });
      }
    }
    await EquipmentAttribute.bulkCreate(attributeCreateArr);
  }
}

async function init() {
  if( process.argv[2] === '--seed' ) {  // 开发环境
    // await db.sync({ force: true });
    // await DepartmentSeed();
    // await UserSeed();
    // await NotificationSeed();
    // await DutyShiftSeed();
    // await WorkingScheduleSeed({
    //   yearStart: 2019,
    //   yearEnd: 2020,
    // });
    // await EquipmentSeed();
    // await InspectionFileAndRecordSeed();
    // await RequestNoteSeed();
  } else if( process.argv[2] === '--production' ) {  // 上线前
    await db.sync({ force: true });
    await SuperUserInitByConfig(superuserConfig);
    await EquipmentInitByConfig(equipmentConfig);
    await WorkingScheduleSeed(workingScheduleConfig);
  }
  console.log('数据库重置成功');
  process.exit(0);
}

init();
